package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.exceptions.LyException;
import com.leyou.item.entity.Sku;
import com.leyou.item.mapper.SkuMapper;
import com.leyou.item.service.SkuService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;

/**
 * @author 虎哥
 */
@Service
public class SkuServiceImpl extends ServiceImpl<SkuMapper, Sku> implements SkuService {

    private static final String UPDATE_STOCK_STATEMENT = "com.leyou.item.mapper.SkuMapper.updateStock";

    @Override
    @Transactional
    public void deductStock(Map<Long, Integer> cartMap) {
        try {
            executeBatch(sqlSession -> {
                //遍历map集合
                for (Map.Entry<Long, Integer> entry : cartMap.entrySet()) {
                    //获取key和value，分别是商品skuId和要修改的数量num
                    Long skuId = entry.getKey();
                    Integer num = entry.getValue();
                    //new一个map集合
                    HashMap<String, Object> map = new HashMap<>();
                    //赋值
                    map.put("id", skuId);
                    map.put("num", num);
                    //指定statement的id和参数
                    sqlSession.update(UPDATE_STOCK_STATEMENT, map);
                }
                //刷新，执行
                sqlSession.flushStatements();
            });
        } catch (Exception e) {
            throw new LyException(400, "库存不足啦！");
        }

       /* //遍历map集合
        for (Map.Entry<Long, Integer> entry : cartMap.entrySet()) {
            //获取key和value，分别是商品skuId和要修改的数量num
            Long skuId = entry.getKey();
            Integer num = entry.getValue();
           *//* //查询商品sku信息
            Sku sku = getById(skuId);
            //判断是否下架或者库存不够
            if (sku.getSold() < num || !sku.getSaleable()) {
                throw new LyException(400,"库存不足或者已经下架了");
            }
            //减库存，加销量
            update().set("stock", sku.getStock() - num)
                    .set("sold", sku.getSold() + num)
                    .eq("id", skuId)
                    .update();*//*

           //new一个map集合
            HashMap<String, Object> map = new HashMap<>();
            //赋值
            map.put("id", skuId);
            map.put("num", num);
            //调mapper里新建的方法减库存
            getBaseMapper().updateStock(map);
        }*/
    }
}
